<template>
  <div id="pageListComponent" class="page-list-component">
    <div
      v-if="maxHeight"
      id="listBody"
      class="list-body"
      :style="{
        height: maxHeight + 'px',
        overflowY: 'auto',
        overflowX: 'hidden',
        background: bgColor
      }"
    >
      <slot />
    </div>
    <div v-if="isShowPagination && isSwitchPageFinish" class="page-style">
      <Pagination
        class="fr"
        :total="total"
        :page="currentPage"
        :limit="pageSize"
        :layout="layout"
        @pagination="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import Pagination from '@/components/Pagination/index.vue'
import { defineProps, ref, toRefs, onMounted, watchEffect, defineEmits, nextTick } from 'vue'

const props = defineProps({
  total: {
    type: Number,
    default: 0
  },
  currentPage: {
    type: Number,
    default: 1
  },
  pageSize: {
    type: Number,
    default: 20
  },
  offsetSize: {
    type: Number,
    default: 0
  },
  bgColor: {
    type: String,
    default: '#FFF'
  },
  layout: {
    type: String,
    default: 'total, sizes, prev, pager, next, jumper'
  },
  isShowPagination: {
    type: Boolean,
    default: true
  }
})

const maxHeight = ref(0)
const isSwitchPageFinish = ref(true)
const { isShowPagination, offsetSize } = toRefs(props)

onMounted(() => {
  nextTick(() => {
    setMaxHeight()
    window.onresize = () => setMaxHeight()
  })
})

watchEffect(() => {})

const setMaxHeight = () => {
  setTimeout(() => {
    // 如果页面有切换动画，则需要延迟700左右，等待页面切换完毕
    const paginationSize = isShowPagination.value ? 65 : 0
    const offsetTop = getOffsetTop()
    const offsetSz = Number(offsetSize.value) || offsetTop
    const ELCARD_PADDINGTOP = 20 // 根据具体的外层el-cardpadding值
    maxHeight.value = document.body.clientHeight - offsetSz - paginationSize - ELCARD_PADDINGTOP - 3
    isSwitchPageFinish.value = true
  }, 50)
}

const getOffsetTop = () => {
  const el = document.getElementById('pageListComponent')
  if (!el) {
    return
  }
  let offsetTop = 0
  let obj = el
  while (obj) {
    const padding =
      ((obj.style && obj.style.paddingTop) || 0) + ((obj.style && obj.style.paddingBottom) || 0)
    offsetTop += obj.offsetTop + padding
    obj = obj.offsetParent
  }
  return offsetTop
}

const emits = defineEmits(['update:currentPage', 'update:pageSize', 'paginationFn'])
const handleCurrentChange = ({ page, limit }) => {
  emits('update:currentPage', page)
  emits('update:pageSize', limit)
  emits('paginationFn', { page, limit })
  document.getElementById('listBody').scrollTop = 0
}
</script>

<style lang="scss" scoped></style>
